﻿/*----------------------------------------------
GLOBAL VARIABLES
----------------------------------------------*/
var _loggedIn;
var _stereotype;
var _userid;
//0 means disabled; 1 means enabled
var popupStatus = 0;
var loginStatus = 0;

/* task timing variable */
var totalTaskTime;         // time taken to complete the task

// URLs
var url_login = document.location.href.replace("SOAAUI.htm", "Services/Login/Login.asmx");
var url_transform = document.location.href.replace("SOAAUI.htm", "Services/Transformation.asmx");
var url_ddl = document.location.href.replace("SOAAUI.htm", "Services/DropdownLists.asmx");
var url_processing = document.location.href.replace("SOAAUI.htm", "Services/Processing/ProcessingService.asmx");
var url_watcher = document.location.href.replace("SOAAUI.htm", "Services/Watcher.asmx");
var url_reliants = document.location.href.replace("SOAAUI.htm", "Services/reliants.asmx");
var url_taskmodel = document.location.href.replace("SOAAUI.htm", "Services/TaskModel.asmx");
var url_expertise = document.location.href.replace("SOAAUI.htm", "Services/Expertise.asmx");

// Expert OLH
var olh_exp_xml = document.location.href.replace("SOAAUI.htm", "Knowledge Base/ObjectHierarchy/Expert/Ex.OLH.1.xml");

var olh_nov_xml_1 = document.location.href.replace("SOAAUI.htm", "Knowledge Base/ObjectHierarchy/Novice/No.OLH.1.xml");
var olh_nov_xml_2 = document.location.href.replace("SOAAUI.htm", "Knowledge Base/ObjectHierarchy/Novice/No.OLH.2.xml");
var olh_nov_xml_3 = document.location.href.replace("SOAAUI.htm", "Knowledge Base/ObjectHierarchy/Novice/No.OLH.3.xml");
var olh_nov_xml_4 = document.location.href.replace("SOAAUI.htm", "Knowledge Base/ObjectHierarchy/Novice/No.OLH.4.xml");

/* *
* OLH XSLT
* */

var olh_exp_xsl = document.location.href.replace("SOAAUI.htm", "Services/Transformation/OLH/OLH.exp.xsl");
var olh_nov_xsl = document.location.href.replace("SOAAUI.htm", "Services/Transformation/OLH/OLH.nov.xsl");

/*----------------------------------------------
USER INTERFACE INITIALISATION FUNCTIONS
----------------------------------------------*/
//Set logged in
$(function() {
    if (_loggedIn !== true) {
        //login
        showLogin();
    }
});
/*----------------------------------------------
UTILITY FUNCTIONS
----------------------------------------------*/
function login() {
    var un = $("#login_username").val();
    var pw = $("#login_password").val();
    var pl = new SOAPClientParameters();
    pl.add("Username", un);
    pl.add("Password", pw);
    SOAPClient.invoke(url_login, "login", pl, true, login_callback);
    
    //set username
    _userid = un;
}

function startTaskTimer() {
    taskTime = new Stopwatch();
    taskTime.start();
    taskInterval = setInterval('updateTaskTime()', 1000);
}

function endTaskTimer() {
    taskTime.stop();
    taskTime.clear();
}

function reserTaskTimer() {
    endTaskTimer();
    startTaskTimer();
}

function updateTaskTime() {
    totalTaskTime = taskTime.elapsed();
    $("#taskTime").html("").append("Total Time: " + taskTime.elapsed());
}

$("#login_button").click(function() {
    var un = $("#login_username").val();
    var pw = $("#login_password").val();
    var pl = new SOAPClientParameters();
    pl.add("Username", un);
    pl.add("Password", pw);
    SOAPClient.invoke(url_login, "login", pl, true, login_callback);

    //set username
    _userid = un;
    
});
function login_callback(r) {
    if (r == "true") {
        hideLogin();
        //show loader div
        showLoader();
        //getUserId();
        getStereoptype();
        transform(1, _stereotype);       
        startTaskTimer();
        
    } else if (r == "false") {
        //display error message
        alert("The Username and Password you entered are not correct. \n\n Please enter correct Username and Password");
        //reset username
        _userid = "";
    } else {
        alert("An unknown error occured");
        //reset username
        _userid = "";
    }
}

// Call Back changes to client stereoptype variable to expert
function isExpert(r) {
    if (r === true) {
        _stereotype = "Expert";
    }
}

function transform(step, stereotype) {
    var xml; //load xml file into here
    var xslt; //load xslt file into here

    if (stereotype === "Novice") {
        //get novice transformation
        //xslt = $.get(olh_nov_xsl).responseText;
        xslt = getFile(olh_nov_xsl);

        //Get xml file
        switch (step) {
            case 4:
                xml = getFile(olh_nov_xml_4);
                break;
            case 3:
                xml = getFile(olh_nov_xml_3);
                break;
            case 2:
                xml = getFile(olh_nov_xml_2);
                break;
            case 1:
                xml = getFile(olh_nov_xml_1);
                break;
            default:
                xml = getFile(olh_nov_xml_1);
                break;
        }
    }

    if (stereotype === "Expert") {
        //Get xml file
        xml = getFile(olh_exp_xml);

        //Get xslt file
        xslt = getFile(olh_exp_xsl);
    }

    //post xslt and xml to server for transformation
    var pl = new SOAPClientParameters();
    pl.add("xml", xml);
    pl.add("xslt", xslt);
    SOAPClient.invoke(url_transform, "TransformXml", pl, true, appendTransform);
}

function getFile(file) {
    return $.ajax({
        type: "GET",
        url: file,
        processData: true,
        async: false
    }).responseText;
}

function appendTransform(s) {
    // Hide loader div
    $('#main').html("").append(s);
    initialiseDdls();
    sortDropDownListByText();
    disableAllDisplays();
}
function getStereoptype() {
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url_login, "getStereoptype", pl, false, r_getStereoptype);    
}
function r_getStereoptype(r) {
    if (r != 'User not found') { //if user exists
        if (r === "Novice") { //if user is novice do a quick check to see if user's past performance may have changed their stereotype to expert

            var pl = new SOAPClientParameters();
            pl.add("userid", _userid);
            SOAPClient.invoke(url_expertise, "isExpert", pl, false, function(r) {
                if (r === true) {     // if performance is that of an expert then set the stereotype to expert
                    _stereotype = "Expert";
                    _loggedIn = true;
                } else { // if performance is still that of a novice then set the stereotype to novice
                    _stereotype = "Novice";
                    _loggedIn = true;
                }
            }); 
        } 
    }
    else
        alert('Please Login to perform any function.');
}

//disable all elements marked as 'display'. If a div is marked as 'display', then disable all elements inside of it
function disableAllDisplays() {
    //find all elements/divs marked disaplay
    var elements = $(".display");
    //disable them by chaging the 'disabled' attribut to true
    for (i = 0; i < elements.length; i++) {
        elements[i].disabled = true;
    }
}

/**************************************************************
Drop down list functions
***************************************************************/
//sorting function source: http://sebastienayotte.wordpress.com/2009/08/04/sorting-drop-down-list-with-jquery/
function sortDropDownListByText() {
    // Loop for each select element on the page.
    $("select").each(function() {
        // Keep track of the selected option.
        var selectedValue = $(this).val();
        // Sort all the options by text. I could easily sort these by val.
        $(this).html($("option", $(this)).sort(function(a, b) {
            return a.text == b.text ? 0 : a.text < b.text ? -1 : 1
        }));
        // Select one option.
        $(this).val(selectedValue);
    });
}

//Populate all the Divs with the appropriate options
function initialiseDdls() {
    var divEls = document.getElementsByTagName("select");
    for (i = 0; i < divEls.length; i++) {
        manageSelect(divEls[i].id);
    }
    hideLoader();
}
function manageSelect(id) {
    // Retreive the list of elements from the database
    var pl = new SOAPClientParameters();
    pl.add("name", id);
    SOAPClient.invoke(url_ddl, "getListElements", pl, false, appendSelect);
}
function appendSelect(r) {
    if (r.length != 0) {
        // Get Element ID
        var id = r[r.length - 1];
        //remove existing options
        removeOptions(id);
        // Add options, except the last one (it is the id of the element)
        for (var i = 0; i < r.length - 1; i++) {
            addOption(id, r[i], r[i]);
        }
    }
}
//Adds an option to a dropdown list
function addOption(id, text, value) {
    var match = false;
    $('#' + id + ' option').each(function() {
        if (value == this.value) match = true;
    });
    if (match) return false;
    $("select#" + id).append('<option value="' + value + '">' + text + '</option>');
}
// Removes existing options for a Drop Down list (cleanup before appending new items from DB)
function removeOptions(id) {
    var select = $("select#" + id)
    $(select).find('option').remove();
}
/**************************************************************
SHOW/HIDE LOADER: ALTER SO IT TAKES DIV ID AS INPUT AND SHOWS IT
***************************************************************/
//Shows the loading div
function showLoader() {
    //centre the loader
    centreLoader();
    //show loading item
    if (popupStatus == 0) {
        $("#mask").css({ "opacity": "0.7" }).fadeIn(100);
        //        $("#mask").fadeIn(250);
        $("#loader").css('visibility', 'visible').show().fadeIn(100);
        popupStatus = 1;
    }
}
//Hides the loading div
function hideLoader() {
    if (popupStatus == 1) {
        $("#mask").fadeOut(100);
        $("#loader").css('visibility', 'hidden').show().fadeOut(100);
        popupStatus = 0;
    }
}
function centreLoader() {
    //get data
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#loader").height();
    var popupWidth = $("#loader").width();
    //centre
    $("#loader").css({
        "position": "absolute",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });
}
/**************************************************************
SHOW/HIDE DEPENDENT LOADER: ALTER SO IT TAKES DIV ID AS INPUT AND SHOWS IT
***************************************************************/
//Shows the loading div
function showDependentLoader(dependent) {
    //Find parent div of current dependent, then, search for the loader graphic inside the parent div and make it show.
    var dep = $("#" + dependent).parent();
    $(dep).find(".depholderdiv").css('visibility', 'visible').show().fadeIn(100);
}

//Hides the loading div
function hideDepLoader(dependent) {
    $(".depholderdiv").css('visibility', 'hidden').show().fadeOut(100);
}

/**************************************************************
SHOW/HIDE LOGIN
***************************************************************/
//Shows the login div
function showLogin() {
    //centre the loader
    centreLogin();
    //show loading item
    if (loginStatus == 0) {
        $("#mask").css({ "opacity": "0.7" }).fadeIn(100);
        //        $("#mask").fadeIn(250);
        $("#login").css('visibility', 'visible').show().fadeIn(100);
        loginStatus = 1;
    }
}
//Hides the loading div
function hideLogin() {
    if (loginStatus == 1) {
        $("#mask").fadeOut(100);
        $("#login").css('visibility', 'hidden').show().fadeOut(100);
        loginStatus = 0;
    }
}
function centreLogin() {
    //get data
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#login").height();
    var popupWidth = $("#login").width();
    //centre
    $("#login").css({
        "position": "absolute",
        "top": windowHeight / 2 - popupHeight / 2,
        "left": windowWidth / 2 - popupWidth / 2
    });
}


